# -*- coding: utf-8 -*-
from py2neo import Graph
from igraph import Graph as IGraph
from igraph import plot as plot
from py2neo import Graph,Node,Relationship,NodeSelector,Subgraph
import networkx as nx
from node2vec import Node2Vec

graph = Graph(password = "admin")
query = '''
MATCH (c1:Character)-[r:INTERACTS]->(c2:Character)
RETURN c1.name, c2.name, r.weight AS weight LIMIT 25
'''

query = '''
MATCH (n:ci_tran)-[r:ci_link_tran]->(m:ci_tran) 
RETURN n.name, m.name, r.tran_count*1.0 AS weight
'''
import datetime

begin = datetime.datetime.now()
edge_list = []
graphdata=graph.run(query)
print datetime.datetime.now()-begin
for record in graphdata:
    edge_list.append(tuple(record))
print len(edge_list)
print datetime.datetime.now()-begin
# G = nx.DiGraph(A) # In case your graph is directed
# G = nx.Graph(ig.get_edgelist()) # In case you graph is undirected

G = nx.DiGraph()   # or DiGraph, MultiGraph, MultiDiGraph, etc
# G.add_weighted_edges_from([('a', 'b', 3.0), ('b', 'c', 7.5), ('c', 'd', 7.5), ('f', 'e', 7.5)])
G.add_weighted_edges_from(edge_list)
print G.number_of_edges()

print datetime.datetime.now()-begin
# Precompute probabilities and generate walks
node2vec = Node2Vec(G, dimensions=32, walk_length=10, num_walks=2, workers=4)
print datetime.datetime.now()-begin
# Embed
model = node2vec.fit(window=10, min_count=1, batch_words=4)  # Any keywords acceptable by gensim.Word2Vec can be passed, `diemnsions` and `workers` are automatically passed (from the Node2Vec constructor)
print datetime.datetime.now()-begin
# Look for most similar nodes
print model.wv.most_similar('7110010117304003101')  # Output node names are always strings

# Save embeddings for later use
model.wv.save_word2vec_format("aa",binary=False)

# Save model for later use
model.save("bb")





print datetime.datetime.now()-begin
# aa = nx.Graph()
# #G.add_nodes_from(id_tag)
# aa.add_edges_from(ig.get_adjedgelist())
#
#
# node2vec = Node2Vec(aa, dimensions=64, walk_length=30, num_walks=200, workers=1)



# pg = ig.pagerank()
# pgvs = []
# for p in zip(ig.vs, pg):
#     print(p)
#     pgvs.append({"name": p[0]["name"], "pg": p[1]})
# pgvs
# write_clusters_query = '''
# UNWIND {nodes} AS n
# MATCH (c:Character) WHERE c.name = n.name
# SET c.pagerank = n.pg
# '''
# graph.run(write_clusters_query, nodes=pgvs)

# clusters = IGraph.community_walktrap(ig, weights="weight").as_clustering()
# nodes = [{"name": node["name"]} for node in ig.vs]
# for node in nodes:
#     idx = ig.vs.find(name=node["name"]).index
#     node["community"] = clusters.membership[idx]
# write_clusters_query = '''
# UNWIND {nodes} AS n
# MATCH (c:Character) WHERE c.name = n.name
# SET c.community = toInt(n.community)
# '''
# graph.run(write_clusters_query, nodes=nodes)
